#include <iostream>
#include <fstream>
#include <vector>
#include "tools.h"
#include "employee.h"
#include "department.h"
#include "servicedao_file_impl.h"

#include <stdlib.h>

using namespace std;
using namespace MH;

void ServiceDaoFileImpl::load(vector<Department*>& v_de)
{
	ifstream input(SE_PATH,ios::in);//read
	if(!input)
	{
		cerr << "in" << endl;
		exit(1);
	}
	
	int id;
	char name[20];
	int num1;//
	int num2;//

	while(1)
	{
		//cout << "===========" << endl;
		input >> id >> name >> num1;
		if(input.eof()) return;//
		Department* de = new Department(id,name);
		cout << de->getId() << " " << de->getName() << " " << num1 << endl;
		v_de.push_back(de);

		//cout << num1 << endl;
		for(int i=0;i<num1;i++)
		{
			//cout << "----" << i << "----" << endl;
			input >> id >> name >> num2;
			if(input.eof()) return;//
			Employee* em = new Employee(id,name,num2/100,num2%100);
			cout << em->getId() << " " << em->getName() << " " << em->getSex() << " " << em->getAge() << endl;
			de->getV_employeep().push_back(em);
		}
	}
}

void ServiceDaoFileImpl::save(vector<Department*>& v_de)
{
	ofstream output(SE_PATH,ios::out|ios::trunc);//write
	if(!output)
	{
		cerr << "out" << endl;
		exit(1);
	}

	while(!v_de.empty())
	{
		Department* de = v_de.back();
		output << de->getId() << " " << de->getName() << " " << (int)de->getV_employeep().size() << endl;
		while(!de->getV_employeep().empty())
		{
			Employee* em = de->getV_employeep().back();
			output << em->getId() << " " << em->getName() << " " << (int)em->getSex()*100+em->getAge() << endl;
			de->getV_employeep().pop_back();
			delete em;
		}
		v_de.pop_back();
		delete de;
	}
}